//
//  ComplaintsViewController.swift
//  Pods
//
//  Created by eme on 2017/4/7.
//
//
/*
 owner:gyh
 update:2017年04月07日16:24:25
 info: 投诉
 */
import UIKit
import UtilCore
import CommonCore
import RickonCore


class ComplaintsViewController: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var TSLX_Btn: UIButton!                          //投诉类型
    
    @IBOutlet weak var Message_TextView: UITextView!                //投诉信息
    
    @IBOutlet weak var lineView: UIView!
    @IBOutlet weak var add_PicCollectionView: UICollectionView!     //上传图片
    
    @IBOutlet weak var type_ImageView: UIImageView!                 //投诉类型右边图片
    
    @IBOutlet weak var complaints_Label: UILabel!                   //投诉类型Label
    
    @IBOutlet weak var commitBtn: UIButton!                         //提交按钮
    
    @IBOutlet weak var JY_Label: UILabel!                           //建议Label
    
    
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var imageArr = [String](){                                      //上传图片字符Arr
        didSet{
            
            self.add_PicCollectionView.reloadData()
        }
    }
    
    var typeModel:ComplainTypeArrModel?                             //投诉类型model
    var ComplainVm:GetComplainVm?                                   //获取投诉类型
    var qiniuVm:Qiniu_Vm?                                           //上传图片
    var detailid:String?                                            //id
    let pick_determineView = UIView()
    let picke = UIPickerView()
    let blackView = UIView()
    var determineBtn:UIButton?
    let window = UIApplication.shared.keyWindow
    var num = 0                                                     //索引值(时间选择器)
    
    /****************************Storyboard 绑定方法区域****************************/
    //提交投诉
    @IBAction func submit_Complaints(_ sender: UIButton) {
        
        if TSLX_Btn.titleLabel?.text == "请选择投诉类型"{
            self.view.toastErrorCode(100054005)
        }else{
            if self.Message_TextView.textColor == UIColor.black && self.Message_TextView.text != ""{
                if ischange(text: self.Message_TextView.text,length: 150) != true
                {
                    self.view.toastErrorCode(100054003)
                }
                else
                {
                    let commitObject:[String:String] = ["picurl":imageArr.joined(separator: ","),"detailid":self.detailid ?? "","complaincommnet":self.Message_TextView.text ?? "","complainTypeId":self.typeModel!.complainType[num].complainTypeId]
                    
                    self.ComplainVm?.submitComplain.onNext(JSONHelper.parseToJson(commitObject as AnyObject) as String)
                }
            }else{
                self.view.toastErrorCode(100054004)
            }
            
        }
    }
    //修改投诉类型
    @IBAction func ChangeComplaints_Type(_ sender: UIButton) {
        
        self.view.endEditing(true)
        self.type_ImageView.image = UIImage.init(named: "filter-attr-spreaded", in: SansaCore.bundle, compatibleWith: nil)
        self.ComplainVm?.getComplainType.onNext("获取类型")
    }
    func createPick(){
        blackView.backgroundColor = UIColor.black
        blackView.alpha = 0.3
        window?.addSubview(blackView)
        blackView.snp.makeConstraints { (make) in
            make.left.right.top.bottom.equalTo(0)
            
        }
        
        self.pick_determineView.backgroundColor = UIColor(hex: "F8F8F8")
        self.pick_determineView.alpha = 1
        window?.addSubview(pick_determineView)
        pick_determineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(196)
        }
        
        self.picke.backgroundColor = UIColor.white
        picke.delegate = self
        picke.dataSource = self
        self.pick_determineView.addSubview(picke)
        picke.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(166)
        }
        
        determineBtn = UIButton(type: .system)
        determineBtn?.setTitle("完成", for: .normal)
        determineBtn?.addTarget(self, action: #selector(ComplaintsViewController.determine), for: .touchUpInside)
        self.pick_determineView.addSubview(determineBtn!)
        determineBtn?.snp.makeConstraints { (make) in
            make.right.equalTo(-10)
            make.top.equalTo(2)
        }
    }
    //完成按钮点击事件
    func determine(){
        self.TSLX_Btn.setTitle(self.typeModel?.complainType[num].compainTypeName, for: .normal)
        self.type_ImageView.image = UIImage.init(named: "down_Image", in: SansaCore.bundle, compatibleWith: nil)
        self.blackView.removeFromSuperview()
        self.pick_determineView.removeFromSuperview()
    }
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
//        self.edgesForExtendedLayout = UIRectEdge.all
        self.lineView.backgroundColor = Theme.v.separate_Line
        self.commitBtn.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
        self.commitBtn.setBackgroundImage(Theme.btn.highlighted.getImage(), for: .highlighted)
        self.commitBtn.setBackgroundImage(Theme.btn.disabled.getImage(), for: .disabled)
        self.customLeftBarButtonItem()
        self.setUpTextView()
        self.setUpCustom_CollectionView()
        commitBtn.titleLabel?.normal_fontSize(15)
        Message_TextView.font = UIFont(name:Theme.font.light,size:14)
        TSLX_Btn.titleLabel?.normal_fontSize(14)
        complaints_Label.normal_fontSize(14)
        JY_Label.normal_fontSize(14)
    }
    func setUpTextView(){
        
        Message_TextView.delegate = self
        Message_TextView.layer.borderWidth = 1
        Message_TextView.layer.borderColor = UIColor(hex: "979797").cgColor
    }
    func setUpCustom_CollectionView(){
        
        let MyLayout = UICollectionViewFlowLayout()
        MyLayout.itemSize = CGSize(width:(UIScreen.main.bounds.width - 75)/4, height:(UIScreen.main.bounds.width - 75)/4)
        MyLayout.scrollDirection = UICollectionViewScrollDirection.vertical
        MyLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
        add_PicCollectionView.collectionViewLayout = MyLayout
        add_PicCollectionView.register(AddNewPicCollectionViewCell.self, forCellWithReuseIdentifier: "cameraCell")
        add_PicCollectionView.register(MessageImageCollectionViewCell.self, forCellWithReuseIdentifier: "imageCell")
        add_PicCollectionView.delegate = self
        add_PicCollectionView.dataSource = self
        
        
    }
    func deleteimage(_ sender:UIButton){
        
        self.imageArr.remove(at: sender.tag)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        //-----------------------------------------
        //上传图片
        
        self.qiniuVm = Qiniu_Vm()
        self.qiniuVm?.uploadImageSuccess.subscribe(onNext:{[unowned self] splicensekey in
            
            
            self.imageArr.append(splicensekey)
            
            
            }).addDisposableTo(disposeBag)
        
        
        self.qiniuVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.qiniuVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //-----------------------------------------
        self.ComplainVm = GetComplainVm()
        
        self.ComplainVm?.backDate.asObserver().subscribe(onNext:{ type in
            
            self.typeModel = type
            self.createPick()
            
            }).addDisposableTo(disposeBag)
        
        self.ComplainVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        self.ComplainVm?.submitbackDate.asObserver().subscribe(onNext:{ result in
            if result == true{
                /**
                 处理请求成功后,禁止触发任何事件
                 */
                let view = UIView()
                self.view.addSubview(view)
                view.snp.makeConstraints({ (make) in
                    make.left.right.top.bottom.equalTo(0)
                })
                self.view.toastCompletion("投诉成功", completion: { _ in
                    _ = self.navigationController?.popViewController(animated: true)
                    
                })
            }
        }).addDisposableTo(disposeBag)
    }
}
extension ComplaintsViewController:UITextViewDelegate{
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if textView.textColor != UIColor.black
        {
            textView.text = ""
            textView.textColor = UIColor.black
            return true
        }
        else
        {
            return true
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text == ""
        {
            textView.text = "欢迎您提出宝贵的建议和意见,您留下的每一个字都讲用于改善我们的服务."
            textView.textColor = UIColor(hex: "c7c7cd")
        }
    }
    func ischange(text:String,length:Int) -> Bool
    {
        let num:NSInteger = (text as NSString).length
        
        if num > length
        {
            return false
            
        }
        else
        {
            return true
        }
    }
}
extension ComplaintsViewController:UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imageArr.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.row {
        case self.imageArr.count:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cameraCell", for: indexPath) as! AddNewPicCollectionViewCell
            return cell
        default:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! MessageImageCollectionViewCell
            cell.deleteButton.tag = indexPath.row
            
            cell.deleteButton.addTarget(self, action: #selector(ComplaintsViewController.deleteimage(_:)), for: .touchUpInside)
            
            cell.customImageView.setUrlImage(self.imageArr[indexPath.row])
            
            return cell
        }
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.row {
        case self.imageArr.count:
            if self.imageArr.count < 3{
                
                selectIcon()
                
            }else{
                self.view.toast("最多上传3张图片")
            }
            
        default:
            break
        }
    }
    //-----------------------------------
    ///改变头像
    func selectIcon()
    {
        let userIconAlert = UIAlertController(title: "请选择操作", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let chooseFromPhotoAlbum = UIAlertAction.init(title: "从相册选择", style: UIAlertActionStyle.default, handler: { UIAlertAction in
            self.ChooseFromPhotoAlbum()
        })
        
        let chooseFromCamera = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default,handler:{ UIAlertAction in
            self.ChooseFromCamera()
        })
        
        let canelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        
        userIconAlert.addAction(canelAction)
        userIconAlert.addAction(chooseFromCamera)
        userIconAlert.addAction(chooseFromPhotoAlbum)
        
        self.present(userIconAlert, animated: true, completion: nil)
        
    }
    
    //MARK:-
    //MARK:从相册选取图片
    func ChooseFromPhotoAlbum() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing = true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //MARK:-
    //MARK:拍照
    func ChooseFromCamera() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing=true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获得编辑后的图片
        if let image = (info as NSDictionary).object(forKey: UIImagePickerControllerEditedImage) as? UIImage  {
            self.qiniuVm?.uploadImageSubject.onNext(image)
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
extension ComplaintsViewController:UIPickerViewDelegate,UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if let model = typeModel{
            return model.complainType.count
        }else{
            return 0
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return typeModel?.complainType[row].compainTypeName
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.num = row
    }
}
